package com.ktwlsoft.archivemanage.domain.business.businessService;

import cn.hutool.core.util.ObjectUtil;
import com.ktwlsoft.archivemanage.config.FileStorageProperties;
import com.ktwlsoft.archivemanage.domain.business.repositoryService.*;
import com.ktwlsoft.archivemanage.domain.business.repositoryService.businessInspect.BusinessInspectRepositoryService;
import com.ktwlsoft.archivemanage.domain.business.repositoryService.guiBusiness.GuiBusinessGuidanceRepositoryService;
import com.ktwlsoft.archivemanage.domain.business.repositoryService.guiBusiness.GuiGuidanceMendListRepositoryService;
import com.ktwlsoft.archivemanage.domain.business.repositoryService.mend.MendListRepositoryService;
import com.ktwlsoft.archivemanage.domain.dao.entity.*;
import com.ktwlsoft.archivemanage.domain.dao.entity.businessInspect.BusinessInspect;
import com.ktwlsoft.archivemanage.domain.dao.entity.guiBusiness.GuiBusinessGuidance;
import com.ktwlsoft.archivemanage.domain.dao.entity.guiBusiness.GuiGuidanceMendList;
import com.ktwlsoft.archivemanage.domain.dao.entity.mend.MendList;
import com.ktwlsoft.archivemanage.domain.dao.entity.register.AccountRegister;
import com.ktwlsoft.archivemanage.payload.mendList.MendListModifyRequest;
import com.ktwlsoft.archivemanage.payload.notifySet.ReportUncommitedUnit;
import com.ktwlsoft.archivemanage.service.security.UserPrincipal;
import com.ktwlsoft.archivemanage.service.utils.DateUtils;
import com.ktwlsoft.archivemanage.service.utils.FileUtils;
import com.ktwlsoft.archivemanage.service.utils.SnowFlake;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.io.File;
import java.math.BigDecimal;
import java.nio.file.Paths;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Year;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Component
public class NotifyMessageScheduleTask {

    private Logger logger = LoggerFactory.getLogger(NotifyMessageScheduleTask.class);

    private NotifySet mendNotifySet;

    private NotifySet guiMendNotifySet;

    private NotifySet annualReportSet;

    private final long mendNotifyWarningRate = 24 * 60 * 60 * 1000L;

    private final NotifyMessageRepositoryService notifyMessageRepositoryService;

    private final NotifySetRepositoryService notifySetRepositoryService;

    private final MendListRepositoryService mendListRepositoryService;

    private final UnitMemberRepositoryService unitMemberRepositoryService;

    private final AnnualReportRepositoryService annualReportRepositoryService;

    private final ArchiveUnitRepositoryService archiveUnitRepositoryService;

    /**抄送*/
    private final CopyToService copyToService;

    /**业务指导整改*/
    private final GuiGuidanceMendListRepositoryService guidanceMendListRepositoryService;

    /**业务指导*/
    private final GuiBusinessGuidanceRepositoryService businessGuidanceRepositoryService;

    /**文件路径*/
    private final FileStorageProperties fileStorageProperties;

    private final BusinessInspectRepositoryService businessInspectRepositoryService;

    public NotifyMessageScheduleTask(NotifyMessageRepositoryService notifyMessageRepositoryService, NotifySetRepositoryService notifySetRepositoryService, MendListRepositoryService mendListRepositoryService, UnitMemberRepositoryService unitMemberRepositoryService, AnnualReportRepositoryService annualReportRepositoryService, ArchiveUnitRepositoryService archiveUnitRepositoryService, CopyToService copyToService, GuiGuidanceMendListRepositoryService guidanceMendListRepositoryService, GuiBusinessGuidanceRepositoryService businessGuidanceRepositoryService, FileStorageProperties fileStorageProperties, BusinessInspectRepositoryService businessInspectRepositoryService) {
        this.notifyMessageRepositoryService = notifyMessageRepositoryService;
        this.notifySetRepositoryService = notifySetRepositoryService;
        this.mendListRepositoryService = mendListRepositoryService;
        this.unitMemberRepositoryService = unitMemberRepositoryService;
        this.annualReportRepositoryService = annualReportRepositoryService;
        this.archiveUnitRepositoryService = archiveUnitRepositoryService;
        this.copyToService = copyToService;
        this.guidanceMendListRepositoryService = guidanceMendListRepositoryService;
        this.businessGuidanceRepositoryService = businessGuidanceRepositoryService;
        this.fileStorageProperties = fileStorageProperties;
        this.businessInspectRepositoryService = businessInspectRepositoryService;
    }

    @PostConstruct
    @Transactional(rollbackFor = Exception.class)
    public void findNotifySet() {
        // find Mend notify set
        this.mendNotifySet = notifySetRepositoryService.findByName("MEND_WARNING");
        this.guiMendNotifySet = notifySetRepositoryService.findByName("GUIDANCE_MEND_WARNING");
        //find annual report notify set
        this.annualReportSet = notifySetRepositoryService.findByName("REPORT_ANNUAL");
    }

    /**
     * 检查整改未提交提醒
     */
    @Scheduled(fixedRate = mendNotifyWarningRate)
    @Transactional(rollbackFor = Exception.class)
    public void scheduleMendNotifyMessage() throws ParseException {
        Long beforeFromNowTimstamp = 0L;
        if (mendNotifySet.getNotifyPeriodUnit() == NotifySet.PeriodUnit.DAY) {
            beforeFromNowTimstamp = mendNotifySet.getNotifyPeriod() * 24 * 60 * 60 * 1000L;
        } else if (mendNotifySet.getNotifyPeriodUnit() == NotifySet.PeriodUnit.MONTH) {
            beforeFromNowTimstamp = mendNotifySet.getNotifyPeriod() * 30 * 24 * 60 * 60 * 1000L;
        }
        List<MendList> mendLists = mendListRepositoryService.findMendListBefore(beforeFromNowTimstamp,new Date());
        //generate notify message
        for (MendList mend : mendLists) {
            UnitMember unitMember = unitMemberRepositoryService.findUnitMemberByArchivistId(mend.getArchivistId());
            if (unitMember == null) {
                logger.warn("生成整改单消息时，检测到整改单对应的档案员不存在，该整改单消息提醒将直接跳过！档案员：" + mend.getArchivist() + ", id:" + mend.getArchivistId());
                continue;
            }
            BusinessInspect inspect = businessInspectRepositoryService.getById(mend.getInspectId());
            String msg = "您有一个检查整改还未提交（得分：%s分/%s分，指导单号：%s）";
            if(ObjectUtil.isNotEmpty(inspect) && "self_or_repeat".equals(inspect.getInspectType())){
                msg = "您有一个检查整改还未提交（满足：%s项/%s项，指导单号：%s）";
                mend.setMark(mend.getMark().divide(new BigDecimal("2"),0,BigDecimal.ROUND_DOWN));
            }
            notifyMessageRepositoryService.insertNotifyMessage(
                    mend.getId(),
                    NotifyMessage.RemindType.MEND_UNCOMMIT,
                    String.format(msg, mend.getMark(), mend.getFullMark(), mend.getGuidNum()),
                    NotifyMessage.BelongBusiness.MEND,
                    unitMember.getRecorder(),
                    unitMember.getRecorderId(),
                    "",
                    0L,
                    5);

            String msg1 = "【档案业务指导服务系统】 检查整改未提交提醒（%s，检查单号：%s，得分：%s分/%s分）";
            if(ObjectUtil.isNotEmpty(inspect) && "self_or_repeat".equals(inspect.getInspectType())){
                msg1 = "【档案业务指导服务系统】 检查整改未提交提醒（%s，检查单号：%s，满足：%s项/%s项）";
            }
            notifyMessageRepositoryService.insertNotifyMessage(
                    mend.getId(),
                    NotifyMessage.RemindType.MEND_UNCOMMIT,
                    String.format(msg1, mend.getArchiveUnit(), mend.getGuidNum(), mend.getMark(), mend.getFullMark()),
                    NotifyMessage.BelongBusiness.MEND,
                    unitMember.getRecorder(),
                    unitMember.getRecorderId(),
                    "",
                    0L,
                    0);
        }
    }

    /**
     * 指导整改未提交提醒
     */
    @Scheduled(fixedRate = mendNotifyWarningRate)
    @Transactional(rollbackFor = Exception.class)
    public void scheduleGuiMendNotifyMessage() throws ParseException {
        Long beforeFromNowTimstamp = 0L;
        if (guiMendNotifySet.getNotifyPeriodUnit() == NotifySet.PeriodUnit.DAY) {
            beforeFromNowTimstamp = guiMendNotifySet.getNotifyPeriod() * 24 * 60 * 60 * 1000L;
        } else if (guiMendNotifySet.getNotifyPeriodUnit() == NotifySet.PeriodUnit.MONTH) {
            beforeFromNowTimstamp = guiMendNotifySet.getNotifyPeriod() * 30 * 24 * 60 * 60 * 1000L;
        }
        //查询规定时间内未整改数据
        List<GuiGuidanceMendList> mendLists = guidanceMendListRepositoryService.findMendListBefore(beforeFromNowTimstamp,new Date());
        for (GuiGuidanceMendList mend : mendLists) {
            if(mend.getGuidanceId() == null || mend.getGuidanceId() <= 0){
                continue;
            }
            GuiBusinessGuidance guidance = businessGuidanceRepositoryService.getById(mend.getGuidanceId());
            if(guidance == null){
                continue;
            }
            UnitMember unitMember = unitMemberRepositoryService.getByUnitId(guidance.getUnitId());
            if (unitMember == null) {
                logger.warn("生成整改单消息时，检测到整改单对应的档案员不存在，该整改单消息提醒将直接跳过");
                continue;
            }
            notifyMessageRepositoryService.insertNotifyMessage(
                    mend.getId(),
                    NotifyMessage.RemindType.GUI_MEND_UNCOMMIT,
                    String.format("您有一个指导整改还未提交（指导单号:%s）",guidance.getGuidanceNum()),
                    NotifyMessage.BelongBusiness.GUI_MEND,
                    unitMember.getRecorder(),
                    unitMember.getRecorderId(),
                    "",
                    0L,
                    5);
            notifyMessageRepositoryService.insertNotifyMessage(
                    mend.getId(),
                    NotifyMessage.RemindType.GUI_MEND_UNCOMMIT,
                    String.format("【档案业务指导服务系统】 指导整改未提交提醒（%s,指导单号:%s）", guidance.getUnit(), guidance.getGuidanceNum()),
                    NotifyMessage.BelongBusiness.GUI_MEND,
                    unitMember.getRecorder(),
                    unitMember.getRecorderId(),
                    "",
                    0L,
                    0);
        }
        //删除视频缩略图
        FileUtils.deleteFile(Paths.get(fileStorageProperties.getUploadDir()).toAbsolutePath().normalize() + File.separator + "thumbnail");
    }

    /**
     * 整改未通过消息提醒
     *
     * @param mendId 整改单号
     */
    public void mendNotPassNotifyMessage(Long mendId,boolean isPass) {
        Account account = UserPrincipal.getCurrentUser();
        MendList mendList = mendListRepositoryService.findById(mendId);
        if(!isPass) {
            BusinessInspect inspect = businessInspectRepositoryService.getById(mendList.getInspectId());
            String msg = "很抱歉！您有一个检查整改未通过验证，请及时调整（得分：%s分/%s分,检查单号：%s ）";
            if(ObjectUtil.isNotEmpty(inspect) && "self_or_repeat".equals(inspect.getInspectType())){
                msg = "很抱歉！您有一个检查整改未通过验证，请及时调整（满足：%s项/%s项,检查单号：%s ）";
                mendList.setMark(mendList.getMark().divide(new BigDecimal("2"),0,BigDecimal.ROUND_DOWN));
            }
            notifyMessageRepositoryService.insertNotifyMessage(
                    mendId,
                    NotifyMessage.RemindType.MEND_LIST_UNPASS,
                    String.format(msg, mendList.getMark(), mendList.getFullMark(), mendList.getGuidNum()),
                    NotifyMessage.BelongBusiness.MEND,
                    mendList.getArchivist(),
                    mendList.getArchivistId(),
                    account != null ? account.getRealName() : "",
                    account != null ? account.getId() : 0L,
                    5
            );
        }else{
            notifyMessageRepositoryService.insertNotifyMessage(
                    mendId,
                    NotifyMessage.RemindType.MEND_LIST_PASS,
                    String.format("【档案业务指导服务系统】您提交的检查整改，已通过验证（检查单号：%s ）", mendList.getGuidNum()),
                    NotifyMessage.BelongBusiness.MEND,
                    mendList.getArchivist(),
                    mendList.getArchivistId(),
                    account != null ? account.getRealName() : "",
                    account != null ? account.getId() : 0L,
                    5
            );
        }
    }

    /**
     * 新增整改消息提醒
     *
     * @param mendId     整改单id
     * @param mark       得分
     * @param fullMark   满分
     * @param guidNum    指导单号
     * @param related    消息接收相关人
     * @param relatedId  消息接收相关人id
     * @param mainBody   主体
     * @param mainBodyId 主体id
     */
    public void newMendNotifyMessage(Long mendId, BigDecimal mark, BigDecimal fullMark, String guidNum, String related, Long relatedId, String mainBody, Long mainBodyId,Long inspectId) {
        Account account = UserPrincipal.getCurrentUser();
        if(account == null){
            account = new Account();
        }
        BusinessInspect inspect = businessInspectRepositoryService.getById(inspectId);
        String msg = "%s为您新增一个检查整改（得分：%s分/%s分,检查单号：%s ）";
        if(ObjectUtil.isNotEmpty(inspect) && "self_or_repeat".equals(inspect.getInspectType())){
            msg = "%s为您新增一个检查整改（满足：%s项/%s项,检查单号：%s ）";
            mark = mark.divide(new BigDecimal("2"),0,BigDecimal.ROUND_DOWN);
        }
        notifyMessageRepositoryService.insertNotifyMessage(
                mendId,
                NotifyMessage.RemindType.MEND_LIST_ADD,
                String.format(msg, account.getRealName(), mark, fullMark, guidNum),
                NotifyMessage.BelongBusiness.MEND,
                related,
                relatedId,
                account.getRealName(),
                account.getId(),
                5
        );
    }

    /**
     * 年度报送未通过提醒
     *
     * @param repostId 年度报送id
     */
    public void annualRepostNotPassNotifyMessage(Long repostId,boolean pass) {
        Report report = annualReportRepositoryService.findAnnualReportDetailById(repostId);
        Account account = UserPrincipal.getCurrentUser();
        if (account == null) {
            logger.warn("在生成消息过程中，未能获取到当前用户，消息生成失败！");
            return;
        }
        if(!pass) {
            notifyMessageRepositoryService.insertNotifyMessage(
                    report.getId(),
                    NotifyMessage.RemindType.ANNUAL_REPORT_UNPASS,
                    String.format("很抱歉！您有一个年度报送报送未通过验证, 请及时调整（单号：%s ）", report.getReportId()),
                    NotifyMessage.BelongBusiness.ANNUAL_REPORT,
                    report.getWritter(),
                    report.getWritterId(),
                    account.getRealName(),
                    account.getId(),
                    5
            );
        }else{
            notifyMessageRepositoryService.insertNotifyMessage(
                    report.getId(),
                    NotifyMessage.RemindType.ANNUAL_REPORT_PASS,
                    String.format("【档案业务指导服务系统】您提交的年度报送，已通过验证（单号：%s ）", report.getReportId()),
                    NotifyMessage.BelongBusiness.ANNUAL_REPORT,
                    report.getWritter(),
                    report.getWritterId(),
                    account.getRealName(),
                    account.getId(),
                    5
            );
        }
    }

    /**
     * 年度报送未提交提醒
     */
    @Scheduled(fixedRate = mendNotifyWarningRate)
    @Transactional(rollbackFor = Exception.class)
    public void annualReportUncommitNotifyMessage() throws ParseException {
        Date now = new Date();
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Long INTERVAL = annualReportSet.getNotifyPeriod() * 24 * 60 * 60 * 1000L;
        Year year = Year.now();
        Date notifyFrom = dateFormat.parse(year.toString() + dateFormat.format(annualReportSet.getNotifyFrom()).substring(4));
        Date notifyTo = dateFormat.parse(year.toString() + dateFormat.format(annualReportSet.getNotifyTo()).substring(4));
        //if now is before the time, don't generate message.
        if (now.before(notifyFrom)) {
            return;
        }
        //query all report-uncommited units
        List<ReportUncommitedUnit> units = notifySetRepositoryService.findAllUnitsOfReportUncommited(DateUtils.dateToStr(new Date(),"yyyy"));

        for (ReportUncommitedUnit u : units) {
            Calendar calendar = Calendar.getInstance();
            calendar.add(Calendar.YEAR, -1);
            // if now is earlier than NotifyFrom and later than NotifyTo, generate notification every day
            if (now.after(notifyFrom) && now.before(notifyTo)) {
                generateMessageOfReportUncommited(u);
            } else {
                // if now is later than NotifyTo, generate notification by period days.
                calendar = Calendar.getInstance();
                calendar.setTime(now);
                calendar.set(Calendar.HOUR_OF_DAY, 0);
                calendar.set(Calendar.MINUTE, 0);
                calendar.set(Calendar.SECOND, 0);
                calendar.set(Calendar.MILLISECOND, 0);
                Date start = calendar.getTime();
                Long realInterval = start.getTime() - notifyTo.getTime();
                if (realInterval % INTERVAL == 0) {
                    generateMessageOfReportUncommited(u);
                }
            }
        }
    }

    private void generateMessageOfReportUncommited(ReportUncommitedUnit u) {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.YEAR, -1);
        notifyMessageRepositoryService.insertNotifyMessage(
                u.getId(),
                NotifyMessage.RemindType.ANNUAL_REPORT_UNCOMMIT,
                String.format("【档案业务指导服务系统】年度报送未提交提醒（%s，%s年的年度报送还未提交）", u.getUnitName(), calendar.get(Calendar.YEAR)),
                NotifyMessage.BelongBusiness.ANNUAL_REPORT,
                u.getRecorder(),
                u.getRecorderId(),
                "",
                0L,
                0
        );
        notifyMessageRepositoryService.insertNotifyMessage(
                u.getId(),
                NotifyMessage.RemindType.ANNUAL_REPORT_UNCOMMIT,
                String.format("您%s年的年度报送还未提交.", calendar.get(Calendar.YEAR)),
                NotifyMessage.BelongBusiness.ANNUAL_REPORT,
                u.getRecorder(),
                u.getRecorderId(),
                "",
                0L,
                5
        );
    }

    /**
     * 新增业务检查提醒
     *
     * @param businessInspect
     */
    public void businessGuideAddNotifyMessage(BusinessInspect businessInspect,List<CopyTo> copyTos) {
        Account account = UserPrincipal.getCurrentUser();
        if(account == null){
            account = new Account();
        }
        if(copyTos != null && copyTos.size() > 0) {
            String msg = "【档案业务指导服务系统】新增业务检查（%s,检查单号:%s,得分:%s分/%s分）";
            if("self_or_repeat".equals(businessInspect.getInspectType())){
                msg = "【档案业务指导服务系统】新增业务检查（%s,检查单号:%s,满足:%s项/%s项）";
            }
            //管理
            NotifyMessage notifyMessage = new NotifyMessage(
                    SnowFlake.getNextId(),
                    new Date(),
                    businessInspect.getId(),
                    NotifyMessage.BelongBusiness.BUSINESS_INSPECT,
                    NotifyMessage.BelongSystem.ARCHIVE_BUSINESS_INSTRUCTION_SYSTEM,
                    NotifyMessage.RemindType.BUSINESS_INSPECT,
                    String.format(msg,
                            businessInspect.getUnitName(),
                            businessInspect.getGuidanceNum(),
                            businessInspect.getMark(),
                            businessInspect.getFullMark()),
                    0,
                    businessInspect.getArchivist(),
                    businessInspect.getArchivistId(),
                    account.getRealName(),
                    account.getId(),
                    0,
                    1);
            notifyMessage.setMessageType(1);
            notifyMessageRepositoryService.getNotifyMessageMapper().insert(notifyMessage);
            //新增抄送人
            for(CopyTo copyTo:copyTos){
                copyTo.setId(SnowFlake.getNextId());
                copyTo.setBusinessId(businessInspect.getId());
                copyTo.setBusinessType(NotifyMessage.BelongBusiness.BUSINESS_INSPECT.getEnName());
                copyTo.setMessageId(notifyMessage.getId());
                copyTo.setCreateName(businessInspect.getCreator());
                copyTo.setCreateId(businessInspect.getCreatorId());
                copyTo.setCreateTime(new Date());
                copyTo.setUpdateName(businessInspect.getCreator());
                copyTo.setUpdateId(businessInspect.getCreatorId());
                copyTo.setUpdateTime(new Date());
            }
            copyToService.getRepositoryService().manyInsert(copyTos);
        }
        String msg = "%s为您新增一条业务检查,待确认（得分：%s分/%s分，检查单号：%s）";
        if("self_or_repeat".equals(businessInspect.getInspectType())){
            msg = "%s为您新增一条业务检查,待确认（满足：%s项/%s项，检查单号：%s）";
            businessInspect.setMark(businessInspect.getMark().divide(new BigDecimal("2"),0,BigDecimal.ROUND_DOWN));
        }
        //用户
        notifyMessageRepositoryService.insertNotifyMessage(
                businessInspect.getId(),
                NotifyMessage.RemindType.BUSINESS_INSPECT,
                String.format(msg,
                        account.getRealName(),
                    businessInspect.getMark(),
                    businessInspect.getFullMark(),
                    businessInspect.getGuidanceNum()),
                NotifyMessage.BelongBusiness.BUSINESS_INSPECT,
                businessInspect.getArchivist(),
                businessInspect.getArchivistId(),
                account.getRealName(),
                account.getId(),
                5
        );
    }

    /**
     * 新增业务指导提醒
     *
     * @param businessGuidance
     */
    public void businessGuidanceAddNotifyMessage(GuiBusinessGuidance businessGuidance,List<CopyTo> copyTos) {
        Account account = UserPrincipal.getCurrentUser();
        if(account == null){
            account = new Account();
        }
        if(copyTos != null && copyTos.size() > 0) {
            //管理
            NotifyMessage notifyMessage = new NotifyMessage(
                    SnowFlake.getNextId(),
                    new Date(),
                    businessGuidance.getId(),
                    NotifyMessage.BelongBusiness.BUSINESS_GUIDANCE,
                    NotifyMessage.BelongSystem.ARCHIVE_BUSINESS_INSTRUCTION_SYSTEM,
                    NotifyMessage.RemindType.BUSINESS_GUIDANCE,
                    String.format("【档案业务指导服务系统】新增业务指导（指导单号:%s,指导人:%s,指导单位:%s）",
                            businessGuidance.getGuidanceNum(),
                            account.getRealName(),
                            businessGuidance.getUnit()),
                    0,
                    businessGuidance.getArchievist(),
                    businessGuidance.getArchievistId(),
                    account.getRealName(),
                    account.getId(),
                    0,
                    1);

            notifyMessage.setMessageType(1);
            notifyMessageRepositoryService.getNotifyMessageMapper().insert(notifyMessage);
            //新增抄送人
            for(CopyTo copyTo:copyTos){
                copyTo.setId(SnowFlake.getNextId());
                copyTo.setBusinessId(businessGuidance.getId());
                copyTo.setBusinessType(NotifyMessage.BelongBusiness.BUSINESS_GUIDANCE.getEnName());
                copyTo.setMessageId(notifyMessage.getId());
                copyTo.setCreateName(businessGuidance.getCreator());
                copyTo.setCreateId(businessGuidance.getCreatorId());
                copyTo.setCreateTime(new Date());
                copyTo.setUpdateName(businessGuidance.getCreator());
                copyTo.setUpdateId(businessGuidance.getCreatorId());
                copyTo.setUpdateTime(new Date());
            }
            copyToService.getRepositoryService().manyInsert(copyTos);
        }
        //用户
        notifyMessageRepositoryService.insertNotifyMessage(
                businessGuidance.getId(),
                NotifyMessage.RemindType.BUSINESS_GUIDANCE,
                String.format("%s为您新增一条业务指导,待确认（指导单号：%s）",
                        account.getRealName(),
                        businessGuidance.getGuidanceNum()),
                NotifyMessage.BelongBusiness.BUSINESS_GUIDANCE,
                businessGuidance.getArchievist(),
                businessGuidance.getArchievistId(),
                account.getRealName(),
                account.getId(),
                5
        );
    }

    public void addAnnualReportWeb(Report report){
        ArchiveUnit reportDetail = archiveUnitRepositoryService.getById(report.getUnitId());
        UnitMember unitMember = unitMemberRepositoryService.getByUnitId(report.getUnitId());
        Account account = UserPrincipal.getCurrentUser();
        notifyMessageRepositoryService.insertNotifyMessage(
                report.getId(),
                NotifyMessage.RemindType.ANNUAL_REPORT_COMMIT,
                String.format("【档案业务指导服务系统】年度报送已提交（%s，%s年的年度报送已提交）", reportDetail.getUnitName(), report.getWriteDate().getValue()),
                NotifyMessage.BelongBusiness.ANNUAL_REPORT,
                unitMember.getRecorder(),
                unitMember.getRecorderId(),
                account != null?account.getRealName():"",
                account != null?account.getId():0L,
                0
        );
    }

    public void addMendListWeb(MendListModifyRequest request){
        MendList mend = mendListRepositoryService.findById(request.getId());
        UnitMember unitMember = unitMemberRepositoryService.findUnitMemberByArchivistId(mend.getArchivistId());
        Account account = UserPrincipal.getCurrentUser();

        BusinessInspect inspect = businessInspectRepositoryService.getById(mend.getInspectId());
        String msg = "【档案业务指导服务系统】检查整改已提交（%s，检查单号：%s，得分：%s分/%s分）";
        if(ObjectUtil.isNotEmpty(inspect) && "self_or_repeat".equals(inspect.getInspectType())){
            msg = "【档案业务指导服务系统】检查整改已提交（%s，检查单号：%s，满足：%s项/%s项）";
            mend.setMark(mend.getMark().divide(new BigDecimal("2"),0,BigDecimal.ROUND_DOWN));
        }
        notifyMessageRepositoryService.insertNotifyMessage(
                request.getId(),
                NotifyMessage.RemindType.MEND_COMMIT,
                String.format(msg, mend.getArchiveUnit(), mend.getGuidNum(), mend.getMark(), mend.getFullMark()),
                NotifyMessage.BelongBusiness.MEND,
                unitMember.getRecorder(),
                unitMember.getRecorderId(),
                account != null?account.getRealName():"",
                account != null?account.getId():0L,
                0);
    }

    public void addMendList(GuiGuidanceMendList mendList){
        GuiBusinessGuidance guidance = businessGuidanceRepositoryService.getById(mendList.getGuidanceId());
        Account account = UserPrincipal.getCurrentUser();
        notifyMessageRepositoryService.insertNotifyMessage(
                mendList.getId(),
                NotifyMessage.RemindType.GUI_MEND_COMMIT,
                String.format("【档案业务指导服务系统】指导整改提交提醒（%s，指导单号：%s）", guidance.getUnit(), guidance.getGuidanceNum()),
                NotifyMessage.BelongBusiness.GUI_MEND,
                guidance.getArchievist(),
                guidance.getArchievistId(),
                account != null?account.getRealName():"",
                account != null?account.getId():0L,
                0);
    }

    public void addMendListMessage(GuiGuidanceMendList mendList){
        GuiBusinessGuidance guidance = businessGuidanceRepositoryService.getById(mendList.getGuidanceId());
        Account account = UserPrincipal.getCurrentUser();
        if(account == null){
            account = new Account();
        }
        notifyMessageRepositoryService.insertNotifyMessage(
                mendList.getId(),
                NotifyMessage.RemindType.ADD_MEND_LIST,
                String.format(" %s为您新增一条指导整改（指导单号：%s）", account.getRealName(), guidance.getGuidanceNum()),
                NotifyMessage.BelongBusiness.GUI_MEND,
                guidance.getArchievist(),
                guidance.getArchievistId(),
                account.getRealName(),
                account.getId(),
                5);
    }

    public void mendListVerify(GuiGuidanceMendList mendList,boolean ispass){
        GuiBusinessGuidance guidance = businessGuidanceRepositoryService.getById(mendList.getGuidanceId());
        if(!ispass){
            notifyMessageRepositoryService.insertNotifyMessage(
                    mendList.getId(),
                    NotifyMessage.RemindType.GUI_MEND_LIST_VERIFY,
                    String.format(" 很抱歉！您有一个指导整改未通过验证，请及时调整（指导单号：%s）", guidance.getGuidanceNum()),
                    NotifyMessage.BelongBusiness.GUI_MEND,
                    guidance.getArchievist(),
                    guidance.getArchievistId(),
                    mendList.getUpdateName(),
                    mendList.getUpdateId(),
                    5);
        }else{
            notifyMessageRepositoryService.insertNotifyMessage(
                    mendList.getId(),
                    NotifyMessage.RemindType.GUI_MEND_LIST_PASS,
                    String.format("【档案业务指导服务系统】您提交的指导整改，已通过验证（指导单号：%s）", guidance.getGuidanceNum()),
                    NotifyMessage.BelongBusiness.GUI_MEND,
                    guidance.getArchievist(),
                    guidance.getArchievistId(),
                    mendList.getUpdateName(),
                    mendList.getUpdateId(),
                    5);
        }
    }

    /**
      * 立档单位注册提醒 on 2020/7/15 11:51
      *
      * @param register register
      */
    public void addRegister(AccountRegister register){
        notifyMessageRepositoryService.insertNotifyMessage(
                register.getId(),
                NotifyMessage.RemindType.REGISTER_SAVE,
                String.format("【档案业务指导服务系统】账号注册(有新的注册申请已提交,注册单位:%s)",register.getUnitName()),
                NotifyMessage.BelongBusiness.REGISTER_SAVE,
                register.getRecorder(),
                0L,
                register.getCreateName(),
                register.getCreateId(),
                0);
    }
}
